package com.speedchina.permission.base.exception;

import com.speedchina.framework.exception.AssertException;
import com.speedchina.framework.exception.BException;
import com.speedchina.framework.exception.BaseSqlException;
import com.speedchina.framework.model.R;
import com.speedchina.permission.base.util.WeChatRobot;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

/**
 * 全局异常捕捉处理类
 *
 * @author hank
 * @create 2021-04-07 上午10:39
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(AssertException.class)
    public R handleAssertException(AssertException e) {
        this.sendErrorAlarm(e);
        return R.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(BaseSqlException.class)
    public R handleBaseSqlException(BaseSqlException e) {
        this.sendErrorAlarm(e);
        return R.error(e.getMessage());
    }

    @ExceptionHandler(BException.class)
    public R handleBException(BException e) {
        this.sendErrorAlarm(e);
        return R.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        // 此处可统一处理异常，比如增加 消息预警
        this.sendErrorAlarm(e);
        return R.error(e.getMessage());
    }
    // other...

    protected void sendErrorAlarm(Exception e) {
        // todo 临时 代码 用 请后续替换
        WeChatRobot robot = new WeChatRobot("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d584be32-6964-4332-99ca-691d1ad8bfa51");
        StringBuffer str = new StringBuffer("错误类型:");
        String msg = null;
        if(e instanceof AssertException) {
            msg = ((AssertException) e).getMsg();
            str.append("业务逻辑错误");
        } else if(e instanceof BaseSqlException) {
            msg = e.getMessage();
            str.append("数据库错误");
        } else if(e instanceof BException) {
            msg = ((BException) e).getMsg();
            str.append("其他逻辑错误");
        } else{
            msg = e.getMessage() == null ? e.getCause().toString() : e.getLocalizedMessage();
            str.append("未处理异常");
        }
        str.append("\n").append(msg);

        try {
            robot.text(str.toString(), new String[]{"@all"}, null);
        }catch (IOException ex){}
    }

}
